<!--
 * @Version: 1.0
 * @Autor:
 * @Date: 2021-03-15 10:59:39
 * @LastEditors: Please set LastEditors
 * @LastEditTime: 2021-09-01 13:29:42
 * @Description:
-->
<template>
  <div>
    <el-card v-loading="loading" class="app-container content_box" shadow="always">
      <div class="header_title_box">
        <h2>基本信息</h2>
      </div>
      <div>
        <el-form :ref="formName" :model="formFieldsData" :rules="rules" inline class="dialog-form-expand2">
          <el-form-item label="模板名称" :label-width="formLabelWidth" prop="name">
            <el-input v-model.trim="formFieldsData.name" :disabled="disabled" placeholder="请输入模板名称" autocomplete="off" clearable style="width:247px" />
          </el-form-item>
          <el-form-item label="客户选择" :label-width="formLabelWidth" prop="company_id">
            <el-select v-model="formFieldsData.company_id" :disabled="disabled" placeholder="请选择客户" filterable clearable style="width:247px">
              <el-option v-for="item in optionCompany" :key="item.value" :label="item.label" :value="item.value" />
            </el-select>
          </el-form-item>
        </el-form>
      </div>
      <div class="header_title_box">
        <h2 style="margin-right:50px">
          台阶费设置
          <el-tooltip placement="top-start" effect="light">
            <div slot="content">
              <p>1.计算商品基础运价时，若商品的计费重量 小于 90lbs,但是商品oversize参数 大于 130英寸，则计费重量按照90lbs计算</p>
              <p>2.计算商品运价时，若商品的计费重量有小数，则向上取整。比如商品为22.1，则计费重量按照23算</p>
              <p>计费重量取的是毛重(美制)和体积重（美制）的取大的那一个</p>
            </div>
            <i class="el-icon-question" />
          </el-tooltip>
        </h2>
        <div v-if="!disabled">
          <el-button type="primary" size="mini" icon="el-icon-plus" @click="addField">新增</el-button>
          <el-button type="success" size="mini" icon="el-icon-upload" @click="formVisibleFile=true">导入</el-button>
          <el-button v-if="selectedIdsFather.length>0" type="danger" size="mini" icon="el-icon-delete" @click="delField">批量删除</el-button>
        </div>
      </div>
      <div style="max-height:500px;overflow: auto; margin-bottom:20px">
        <el-form ref="formData" :rules="model.rules" :model="model" class="dialog-form-expand3">
          <el-table :data="model.fields" tooltip-effect="dark" style="width: 100%" border fit @selection-change="handleSelectMultiFather">
            <el-table-column v-if="!disabled" align="center" type="selection" width="55" />
            <el-table-column v-if="!disabled" align="center" label="操作" width="150">
              <template slot-scope="field">
                <el-button type="danger" size="mini" icon="el-icon-delete" @click="deleteField(field.row)" />
              </template>
            </el-table-column>
            <el-table-column align="center" label="重量范围(lbs）">
              <template slot-scope="field">
                <el-form-item :prop="'fields.' + field.$index + '.weight'" :rules="model.rules.weight">
                  <el-input v-model.trim="field.row.weight" :disabled="field.row.disabled" size="mini" placeholder="输入重量（整数）" autocomplete="off" clearable />
                </el-form-item>
              </template>
            </el-table-column>
            <el-table-column align="center" label="Zone2">
              <template slot-scope="field">
                <el-form-item :prop="'fields.' + field.$index + '.zone2'" :rules="model.rules.zone2">
                  <el-input v-model.trim="field.row.zone2" :disabled="field.row.disabled" size="mini" placeholder="最多包含2位小数" autocomplete="off" clearable />
                </el-form-item>
              </template>
            </el-table-column>
            <el-table-column align="center" label="Zone3">
              <template slot-scope="field">
                <el-form-item :prop="'fields.' + field.$index + '.zone3'" :rules="model.rules.zone2">
                  <el-input v-model.trim="field.row.zone3" :disabled="field.row.disabled" size="mini" placeholder="最多包含2位小数" autocomplete="off" clearable />
                </el-form-item>
              </template>
            </el-table-column>
            <el-table-column align="center" label="Zone4">
              <template slot-scope="field">
                <el-form-item :prop="'fields.' + field.$index + '.zone4'" :rules="model.rules.zone2">
                  <el-input v-model.trim="field.row.zone4" :disabled="field.row.disabled" size="mini" placeholder="最多包含2位小数" autocomplete="off" clearable />
                </el-form-item>
              </template>
            </el-table-column>
            <el-table-column align="center" label="Zone5">
              <template slot-scope="field">
                <el-form-item :prop="'fields.' + field.$index + '.zone5'" :rules="model.rules.zone2">
                  <el-input v-model.trim="field.row.zone5" :disabled="field.row.disabled" size="mini" placeholder="最多包含2位小数" autocomplete="off" clearable />
                </el-form-item>
              </template>
            </el-table-column>
            <el-table-column align="center" label="Zone6">
              <template slot-scope="field">
                <el-form-item :prop="'fields.' + field.$index + '.zone6'" :rules="model.rules.zone2">
                  <el-input v-model.trim="field.row.zone6" :disabled="field.row.disabled" size="mini" placeholder="最多包含2位小数" autocomplete="off" clearable />
                </el-form-item>
              </template>
            </el-table-column>
            <el-table-column align="center" label="Zone7">
              <template slot-scope="field">
                <el-form-item :prop="'fields.' + field.$index + '.zone7'" :rules="model.rules.zone2">
                  <el-input v-model.trim="field.row.zone7" :disabled="field.row.disabled" size="mini" placeholder="最多包含2位小数" autocomplete="off" clearable />
                </el-form-item>
              </template>
            </el-table-column>
            <el-table-column align="center" label="Zone8">
              <template slot-scope="field">
                <el-form-item :prop="'fields.' + field.$index + '.zone8'" :rules="model.rules.zone2">
                  <el-input v-model.trim="field.row.zone8" :disabled="field.row.disabled" size="mini" placeholder="最多包含2位小数" autocomplete="off" clearable />
                </el-form-item>
              </template>
            </el-table-column>
          </el-table>
        </el-form>
      </div>
      <div class="header_title_box">
        <h2 style="margin-right:50px">
          保价费设置
        </h2>
      </div>
      <div>
        <el-form :ref="formName2" :model="formFieldsData2" :rules="rules" inline class="dialog-form-expand2">
          <el-form-item label="保费单价(usd)" :label-width="formLabelWidth" prop="insurance_fee">
            <el-input v-model.trim="formFieldsData2.insurance_fee" :disabled="disabled" placeholder="请输入保费单价(usd)" autocomplete="off" clearable style="width:300px">
              <template slot="append">每100usd</template>
            </el-input>
          </el-form-item>
        </el-form>
      </div>
      <div class="header_title_box">
        <h2 style="margin-right:50px">
          其他附加费设置
        </h2>
      </div>
      <div>
        <el-form :ref="formName3" :model="formFieldsData3" :rules="rules">
          <el-form-item align="center" label="Additional Handling Surcharge（额外处理费）" label-width="314px">
            <div class="filter-selection">
              <div class="mb10">
                <el-form-item class="inline-form-box" :label-width="formLabelWidth2" inline label="若毛重>" prop="gross_weight" :rules="rules.size">
                  <el-input v-model.trim="formFieldsData3.gross_weight" :disabled="disabled" placeholder="输入毛重" autocomplete="off" clearable style="width:300px">
                    <template slot="append">lbs</template>
                  </el-input>
                </el-form-item>
              </div>
              <div class="mb10">
                <el-form-item class="inline-form-box" :label-width="formLabelWidth2" label="则 收取" prop="gross_weight_fee" :rules="rules.fee">
                  <el-input v-model.trim="formFieldsData3.gross_weight_fee" :disabled="disabled" placeholder="输入费用" autocomplete="off" clearable style="width:300px">
                    <template slot="append">/包裹</template>
                  </el-input>
                </el-form-item>
              </div>
            </div>
            <div class="filter-selection">
              <div class="mb10">
                <el-form-item class="inline-form-box" :label-width="formLabelWidth2" label="或最长边 >" prop="big_side_length" :rules="rules.size">
                  <el-input v-model.trim="formFieldsData3.big_side_length" :disabled="disabled" placeholder="输入长边" autocomplete="off" clearable style="width:300px">
                    <template slot="append">英寸</template>
                  </el-input>
                </el-form-item>
              </div>
              <div class="mb10">
                <el-form-item class="inline-form-box" :label-width="formLabelWidth2" label="则 收取" prop="big_side_length_fee" :rules="rules.fee">
                  <el-input v-model.trim="formFieldsData3.big_side_length_fee" :disabled="disabled" placeholder="输入长边费用" autocomplete="off" clearable style="width:300px">
                    <template slot="append">/包裹</template>
                  </el-input>
                </el-form-item>
              </div>
            </div>
            <div class="filter-selection">
              <div class="mb10">
                <el-form-item class="inline-form-box" :label-width="formLabelWidth2" label="或次长边 >" prop="second_side_length" :rules="rules.size">
                  <el-input v-model.trim="formFieldsData3.second_side_length" :disabled="disabled" placeholder="输入长边" autocomplete="off" clearable style="width:300px">
                    <template slot="append">英寸</template>
                  </el-input>
                </el-form-item>
              </div>
              <div class="mb10">
                <el-form-item class="inline-form-box" :label-width="formLabelWidth2" label="则 收取" prop="second_side_length_fee" :rules="rules.fee">
                  <el-input v-model.trim="formFieldsData3.second_side_length_fee" :disabled="disabled" placeholder="输入长边费用" autocomplete="off" clearable style="width:300px">
                    <template slot="append">/包裹</template>
                  </el-input>
                </el-form-item>
              </div>
            </div>
          </el-form-item>
          <el-form-item align="center" label="Oversize（超大超尺寸费）" label-width="314px">
            <div class="filter-selection">
              <div class="mb10">
                <el-form-item class="inline-form-box" :label-width="formLabelWidth2" label="或" prop="oversize_min_size" :rules="rules.size">
                  <el-input v-model.trim="formFieldsData3.oversize_min_size" :disabled="disabled" placeholder="输入最小Oversize" autocomplete="off" clearable style="width:300px">
                    <template slot="append">英寸</template>
                  </el-input>
                </el-form-item>
              </div>
              <div class="mb10">
                <el-form-item class="inline-form-box" :label-width="formLabelWidth2" label="<Oversize参数<" prop="oversize_max_size" :rules="rules.size">
                  <el-input v-model.trim="formFieldsData3.oversize_max_size" :disabled="disabled" placeholder="最大Oversize" autocomplete="off" clearable style="width:300px">
                    <template slot="append">英寸</template>
                  </el-input>
                </el-form-item>
              </div>
              <div class="mb10">
                <el-form-item class="inline-form-box" :label-width="formLabelWidth2" label="则 收取" prop="oversize_fee" :rules="rules.fee">
                  <el-input v-model.trim="formFieldsData3.oversize_fee" :disabled="disabled" placeholder="输入费用" autocomplete="off" clearable style="width:300px">
                    <template slot="append">/包裹</template>
                  </el-input>
                </el-form-item>
              </div>
            </div>
            <div class="filter-selection">
              <div class="mb10">
                <el-form-item class="inline-form-box" :label-width="formLabelWidth2" label="或Oversize参数 >" prop="oversize_other_size" :rules="rules.size">
                  <el-input v-model.trim="formFieldsData3.oversize_other_size" :disabled="disabled" placeholder="输入长边" autocomplete="off" clearable style="width:300px">
                    <template slot="append">英寸</template>
                  </el-input>
                </el-form-item>
              </div>
              <div class="mb10">
                <el-form-item class="inline-form-box" :label-width="formLabelWidth2" label="则 收取" prop="oversize_other_size_fee" :rules="rules.fee">
                  <el-input v-model.trim="formFieldsData3.oversize_other_size_fee" :disabled="disabled" placeholder="输入长边费用" autocomplete="off" clearable style="width:300px">
                    <template slot="append">/包裹</template>
                  </el-input>
                </el-form-item>
              </div>
            </div>
          </el-form-item>
          <el-form-item label="偏远地区附加费" :label-width="formLabelWidth" prop="remote_fee">
            <el-input v-model.trim="formFieldsData3.remote_fee" :disabled="disabled" placeholder="请输入模板名称" autocomplete="off" clearable style="width:300px">
              <template slot="append">/包裹</template>
            </el-input>
          </el-form-item>
          <el-form-item label="超偏远地区附加费" :label-width="formLabelWidth" prop="super_remote_fee">
            <el-input v-model.trim="formFieldsData3.super_remote_fee" :disabled="disabled" placeholder="请输入模板名称" autocomplete="off" clearable style="width:300px">
              <template slot="append">/包裹</template>
            </el-input>
          </el-form-item>
        </el-form>
      </div>
      <div class="footer-center">
        <el-button :type="type === 'info' ? 'primary' : 'default'" @click="handleCancelPath">{{ type === 'info' ? '返 回' : '取 消' }}</el-button>
        <el-button v-if="!disabled" type="primary" @click="handleSubmitNew">确 定</el-button>
      </div>
      <!-- 导入 -->
      <importExcel :form-visible.sync="formVisibleFile" @download="downLoad" @changeData="changeData" />
    </el-card>
  </div>
</template>

<script>
import formOperate from '@/layout/mixin/formOperate'
import {
  companyList
} from '@/utils/publicData'
import importExcel from '../component/importExcel.vue'
import { downloadStream } from '@/utils/index'
export default {
  name: 'BasicsLogisticsConfigAdd',
  components: { importExcel },
  mixins: [formOperate],
  data() {
    return {
      formVisibleFile: false,
      loading: false,
      selectedIdsFather: [],
      id: '',
      formFieldsData: {
        name: '',
        company_id: ''
      },
      formFieldsData2: {
        insurance_fee: ''
      },
      formFieldsData3: {
        remote_fee: '',
        super_remote_fee: '',
        gross_weight: '',
        gross_weight_fee: '',
        big_side_length: '',
        big_side_length_fee: '',
        second_side_length: '',
        second_side_length_fee: '',
        oversize_other_size: '',
        oversize_other_size_fee: '',
        oversize_min_size: '',
        oversize_max_size: '',
        oversize_fee: ''
      },
      formLabelWidth2: '120px',
      formName2: 'logisticsFeeConfig2',
      formName3: 'logisticsFeeConfig3',
      formName: 'logisticsFeeConfig',
      formLabelWidth: '150px',
      formVisible: false,
      outerVisible: false,
      optionCompany: [],
      rules: {
        name: [{ required: true, message: '请输入模板名称', trigger: 'blur' }],
        company_id: [{ required: true, message: '请选择客户', trigger: 'change' }],
        fee: [{ required: true, message: '请输入费用', trigger: 'blur' }, { pattern: /\d+(\.[0-9]{1,2}){0,1}$/, message: '只能输入数字,最多二位小数', trigger: 'change' }],
        size: [{ required: true, message: '请输入尺寸', trigger: 'blur' }, { pattern: /\d+(\.[0-9]{1,2}){0,1}$/, message: '只能输入数字,最多二位小数', trigger: 'change' }],
        insurance_fee: [{ required: true, message: '请输入费用', trigger: 'blur' }, { pattern: /\d+(\.[0-9]{1,2}){0,1}$/, message: '只能输入数字,最多二位小数', trigger: 'change' }],
        remote_fee: [{ required: true, message: '请输入偏远地区附加费', trigger: 'blur' }, { pattern: /\d+(\.[0-9]{1,2}){0,1}$/, message: '只能输入数字,最多二位小数', trigger: 'change' }],
        super_remote_fee: [{ required: true, message: '请输入超偏远地区附加费', trigger: 'blur' }, { pattern: /\d+(\.[0-9]{1,2}){0,1}$/, message: '只能输入数字,最多二位小数', trigger: 'change' }],
        zone2: [{ required: true, message: '必填字段', trigger: 'blur' }, { pattern: /\d+(\.[0-9]{1,2}){0,1}$/, message: '只能输入数字,最多二位小数', trigger: 'change' }]
      },
      model: {
        rules: {
          weight: [{ required: true, message: '必填字段', trigger: 'change' }, { pattern: /^[0-9]*$/, message: '只能输入整数', trigger: 'change' }],
          zone2: [{ required: true, message: '必填字段', trigger: 'blur' }, { pattern: /\d+(\.[0-9]{1,2}){0,1}$/, message: '只能输入数字,最多二位小数', trigger: 'change' }]
        },
        fields: [this.getColumn()]
      },
      type: '',
      disabled: false
    }
  },
  created() {
    const vm = this
    vm.id = vm.$route.query.id || ''
    vm.type = vm.$route.query.type || ''
    vm.disabled = vm.type === 'info'
    if (vm.id) {
      vm.handleUpdateNew(vm.id)
    }
    companyList().then((data) => {
      vm.optionCompany = data
    })
  },
  methods: {
    // 导入物流台阶费模板下载
    changeData(data) {
      this.model.fields = data
    },
    // 下载
    downLoad() {
      const vm = this
      vm.$http
        .get('/logisticsFeeConfig/import/template', { responseType: 'blob' })
        .then((res) => {
          downloadStream(res, '物流台阶费导入模板.xlsx')
        })
    },
    // 选择台阶费设置
    handleSelectMultiFather(data) {
      const vm = this
      vm.selectedIdsFather = []
      data.forEach(item => {
        vm.selectedIdsFather.push(item)
      })
    },
    // 批量删除已添加
    delField() {
      const vm = this
      const dataArr = [...this.model.fields]
      dataArr.map((arr) => {
        if (vm.selectedIdsFather.includes(arr)) {
          vm.model.fields.splice(vm.model.fields.indexOf(arr), 1)
        }
      })
    },
    handleCancelPath() {
      this.$router.push({ path: '/basics/logisticsFeeConfig' })
    },
    // 数据列表
    getColumn() {
      return {
        'weight': '',
        'zone2': '',
        'zone3': '',
        'zone4': '',
        'zone5': '',
        'zone6': '',
        'zone7': '',
        'zone8': ''
      }
    },
    handleUpdateNew(id) {
      this.loading = true
      this.$http.get(`logisticsFeeConfig/${id}`).then(res => {
        const dataObj = res.data
        this.formFieldsData = dataObj
        this.formFieldsData2 = dataObj
        this.formFieldsData3 = dataObj
        if (dataObj.list && dataObj.list.length > 0) {
          this.model.fields = dataObj.list.map((arr) => {
            arr.id = null
            arr.disabled = this.disabled
            return arr
          })
          this.loading = false
        }
        this.loading = false
        this.formVisible = true
      })
    },
    handleSubmitNew() {
      this.$refs['logisticsFeeConfig'].validate((valid) => {
        if (valid) {
          // 判断个人信息
          // 判断至少添加个 台阶费
          if (this.model.fields.length <= 0) {
            return this.$message.error('请选择添加至少一个台阶费设置')
          }
          this.$refs['formData'].validate((validSon) => {
            // 添加
            if (validSon) {
              this.$refs['logisticsFeeConfig2'].validate((valid2) => {
                if (valid2) {
                  this.$refs['logisticsFeeConfig3'].validate((valid3) => {
                    if (valid3) {
                      // 编辑
                      if (this.formFieldsData.id) {
                        this.$http.put(`logisticsFeeConfig/${this.formFieldsData.id}`, this.getData()).then(response => {
                          if (response.code === 10000) {
                            this.$message.success('编辑成功')
                            this.formVisible = false
                            this.$router.push({ path: '/basics/logisticsFeeConfig' })
                          } else {
                            this.$message.error(response.message)
                          }
                        })
                      } else {
                        this.$http.post('logisticsFeeConfig', this.getData()).then(response => {
                          if (response.code === 10000) {
                            this.$message.success('添加成功')
                            this.formVisible = false
                            this.$router.push({ path: '/basics/logisticsFeeConfig' })
                          } else {
                            this.$message.error(response.message)
                          }
                        })
                      }
                    }
                  })
                }
              })
            }
          })
        }
      })
    },
    // 获取添加参数组合
    getData() {
      //  data = this.formFieldsData
      const data = Object.assign({}, this.formFieldsData2, this.formFieldsData3, this.formFieldsData)
      delete data.created_at
      delete data.updated_at
      if (this.model.fields && this.model.fields.length > 0) {
        const dataArr = this.model.fields
        data['logistics'] = dataArr
      }
      return data
    }
  }
}
</script>

<style lang="scss" scoped>
.filter-selection {
  align-items: center;
  flex-wrap: wrap;
  display: flex;
  min-height: 40px;
}
.mb10 {
  margin-bottom: 16px;
}
</style>
